/*Hm9gUKDDwtNjV7Mk8onAzgXlk2sN3YqGeiNBfMPmEAaQ5tb/cjXQzjs3lVWuDzNj*/
import { ajax, print, output, cardCache } from 'nc-lightapp-front';
import { pageConfig } from '../const';
import ampub from 'ampub';
const { components, commonConst, utils } = ampub;
const { StatusUtils } = commonConst;
const { multiLangUtils, msgUtils, cardUtils, getThemeUtils } = utils;
const { getMultiLangByID } = multiLangUtils;
const { showConfirm, MsgConst, showMessage } = msgUtils;
const { faQueryAboutUtils, LoginContext, ScriptReturnUtils } = components;
const { openAssetCardByChooseRow } = faQueryAboutUtils;
const { UISTATE, VOSTATUS } = StatusUtils;
const { setBillFlowBtnsVisible, setCardValue, setHeadAreaData, setBtnsVisibleBySagaStatus } = cardUtils;
const { getContext, loginContextKeys } = LoginContext;
const { getScriptCardReturnData, getCommitParam } = ScriptReturnUtils;
import fa from 'fa';
const { fa_components } = fa;
const { ImageMng } = fa_components;
const { faImageScan, faImageView } = ImageMng;
const {
	btn_body,
	btn_head,
	resourceCode,
	printNodekey,
	listRouter,
	url,
	formId,
	tableId,
	pkField,
	bodyPkField,
	pagecode,
	bill_type,
	dataSource,
	browseBtns,
	editBtns,
	printFilename,
	alarmId
} = pageConfig;

export default function(props, id) {
	switch (id) {
		case btn_head.ADD:
			doAdd.call(this, props);
			break;

		case btn_head.EDIT:
			doEdit.call(this, props);
			break;

		case btn_head.SAVE:
			doSave.call(this, props);
			break;

		case btn_head.COMMIT:
			commitAction.call(this, props, 'SAVE', 'commit');
			break;

		case btn_head.SAVECOMMIT:
			commitAction.call(this, props, 'SAVE', 'saveCommit');
			break;

		case btn_head.UNCOMMIT:
			commitAction.call(this, props, 'UNSAVE', '');
			break;

		case btn_head.DELETE:
			doDelete.call(this, props);
			break;

		case btn_head.CANCEL:
			doCancel.call(this, props);
			break;

		case btn_head.BATCHALTER:
			batchAlter.call(this, props);
			break;

		case btn_body.ADD_LINE:
			addLine.call(this, props);
			break;

		case btn_body.DELETE_LINE:
			delLine.call(this, props);
			break;

		case btn_head.REFRESH:
			refresh.call(this, props);
			break;

		case btn_head.PRINT:
			printTemp.call(this, props);
			break;

		case btn_head.OUTPUT:
			outputTemp.call(this, props);
			break;

		case btn_head.FARECEIPTSCAN:
			faReceiptScan.call(this, props);
			break;

		case btn_head.FARECEIPTSHOW:
			faReceiptShow.call(this, props);
			break;

		case btn_head.QUERYABOUTASSET:
			queryAboutAsset.call(this, props);
			break;

		case btn_head.QUERYABOUTBUDGET:
			queryAboutBudgetAction.call(this, props);
			break;

		case btn_head.COPY:
			copyAction.call(this, props);
			break;

		case btn_head.ATTACHMENT:
			attachmentAction.call(this, props);
			break;

		case btn_head.QUERYABOUTBILLFLOW:
			openApproveAction.call(this, props);
			break;

		default:
			break;
	}
}

//修改
function doEdit(props) {
	let pk = props.form.getFormItemsValue(formId, pkField).value;
	if (!pk || pk == 'undefined' || pk == 'null') {
		pk = props.getUrlParam('id');
	}
	if (!pk || pk == 'undefined' || pk == 'null') {
		return;
	}
	props.cardTable.closeExpandedRow(tableId);
	ajax({
		url: url.EDIT,
		data: {
			pk,
			resourceCode
		},
		success: (res) => {
			let { success, data } = res;
			if (success) {
				if (data) {
					showMessage.call(this, props, { color: 'warning', content: data });
				} else {
					setStatus.call(this, props, UISTATE.edit);
					props.form.setFormItemsDisabled(formId, {
						pk_org_v: true,
						pk_org: true
					});
					// 更新 saga_frozen 值为 0【由于界面上该字段的值不自动更新】
					props.form.setFormItemsValue(formId, {
						saga_frozen: { value: '0' }
					});
				}
			}
		}
	});
}

//审批详情
function openApproveAction(props) {
	let pk_newasset = props.form.getFormItemsValue(formId, 'pk_newasset');
	let transi_type = props.form.getFormItemsValue(formId, 'transi_type');
	this.setState({
		showApprove: true,
		transi_type: transi_type.value,
		pk_newasset: pk_newasset.value
	});
}

// 预算联查
function queryAboutBudgetAction(props) {
	let pk_newasset = props.form.getFormItemsValue(formId, 'pk_newasset');
	ajax({
		url: url.QUERYABOUTBUDGET,
		data: {
			pk: pk_newasset.value
		},
		success: (res) => {
			if (res.data.hint != undefined) {
				showMessage.call(this, props, { color: 'warning', content: res.data.hint });
			} else {
				this.setState({
					show: true,
					sourceData: res.data
				});
			}
		}
	});
}

//附件
function attachmentAction(props) {
	let billId = props.form.getFormItemsValue(formId, pkField).value;
	props.ncUploader.show(`${pagecode}-uploader`, {
		billId: 'fa/newasset/' + billId
	});
}

/**
 * 列表态复制数据
 * @param {*} props 
 * @param {*} pk 
 */
export function copyDataByPk(props, pk) {
	ajax({
		url: url.QUERY_CARD, //此处复制方法为前台处理，如果后台处理，则 url: url.QUERY_COPY
		data: {
			pagecode,
			pk
		},
		success: (res) => {
			let { success, data } = res;
			if (success) {
				setValue.call(this, props, data);
				copyAction.call(this, props);
			}
		}
	});
}

// 复制
function copyAction(props) {
	//业务日期
	let business_date = getContext(loginContextKeys.businessDate);
	// 清空表头部分字段
	props.form.setFormItemsValue(formId, {
		business_date: { value: business_date },
		pk_newasset: { value: null, display: null },
		controlrule: { value: null, display: null },
		ts: { value: null, display: null },
		bill_code: { value: null, display: null },
		billmaker: { value: null, display: null },
		billmaketime: { value: null, display: null },
		auditor: { value: null, display: null },
		audittime: { value: null, display: null },
		check_opinion: { value: null, display: null },
		bill_status: { display: getMultiLangByID('statusUtils-000000') /* 国际化处理： 自由态*/, value: '0' },
		creator: { value: null, display: null },
		creationtime: { value: null, display: null },
		modifier: { value: null, display: null },
		modifiedtime: { value: null, display: null },
		saga_status: { value: null, display: null },
		saga_frozen: { value: null, display: null },
		saga_gtxid: { value: null, display: null },
		saga_btxid: { value: null, display: null },
	});
	// 清空表体相关字段信息
	let body = props.cardTable.getAllData(tableId);
	body.rows.map((ele) => {
		ele.values.pk_newasset = {};
		ele.values.pk_newasset_b = {};
		ele.values.ts = {};
		ele.values.pk_card = {}; // 卡片编号
		ele.values.card_code = {};
		ele.values.asset_code = {}; //资产编码
	});
	props.cardTable.setTableData(tableId, body);
	let pk_org = props.form.getFormItemsValue(formId, 'pk_org_v');
	if (pk_org && pk_org.value) {
		//设置财务组织为不可编辑
		props.form.setFormItemsDisabled(formId, { pk_org_v: true });
	}
	setStatus.call(this, props, UISTATE.add);
}

//联查卡片
function queryAboutAsset(props) {
	openAssetCardByChooseRow.call(this, props, tableId);
}

//影像扫描
function faReceiptScan(props) {
	let imageData = {
		pagecode,
		formId,
		tableId,
		pkField
	};
	faImageScan(props, imageData);
}

//影像查看
function faReceiptShow(props) {
	let imageData = {
		pagecode,
		formId,
		tableId,
		pkField
	};
	faImageView(props, imageData);
}

/**
 * 表肩批改
 */
function batchAlter(props) {
	let num = props.cardTable.getNumberOfRows(tableId);
	if (num <= 1) {
		return;
	}
	//获取原始数据
	let changeData = props.cardTable.getTableItemData(tableId);
	let index = changeData.batchChangeIndex; // 原始数据行号
	let key = changeData.batchChangeKey; // 原始数据key
	let value = changeData.batchChangeValue; // 原始数据value

	//多语字段得到的不是字符串，需要做一下转换
	if (value != null && typeof value == 'object') {
		value = value[key].value;
	}

	//先判断是否允许批改
	if (key === 'pk_usedept' || key === 'pk_assetuser') {
		//使用部门、使用人
		//如果【使用权】这一列的值不相同，不允许批改
		let pk_equiporgs = props.cardTable.getColValue(tableId, 'pk_equiporg_v');
		pk_equiporgs = getArrayAttribute(pk_equiporgs, 'value');
		if (pk_equiporgs.length > 1) {
			// [使用权] 列中的值不一致，不允许批改！
			showMessage(props, { content: getMultiLangByID('201201512A-000011'), color: 'warning' });
			return;
		}
	}
	if (key === 'pk_mandept_v' || key === 'pk_mandept') {
		//管理部门
		//如果【货主管理组织】这一列的值不相同，不允许批改
		let pk_ownerorgs = props.cardTable.getColValue(tableId, 'pk_ownerorg_v');
		pk_ownerorgs = getArrayAttribute(pk_ownerorgs, 'value');
		if (pk_ownerorgs.length > 1) {
			//[货主管理组织] 列中的值不一致，不允许批改！
			showMessage(props, { content: getMultiLangByID('201201512A-000012'), color: 'warning' });
			return;
		}
	}

	//调用后端的批改操作
	let cardData = props.createMasterChildDataSimple(pagecode, formId, tableId);
	ajax({
		url: url.BATCHALTER,
		data: {
			card: cardData,
			batchChangeIndex: index, // 原始数据行号
			batchChangeKey: key, // 原始数据key
			batchChangeValue: value, // 原始数据value
			// 原始数据所在的vo，对应聚合VO中的tableCodes，一主一子可为空，一主多子要传对应的值
			tableCode: ''
		},
		success: (res) => {
			let { success, data } = res;
			if (success) {
				//把数据设置到界面上
				setValue.call(this, props, data);
				//由于后台批改要根据是否是空行进行判断，所以清空处理放在success之后
				//批改货主管理组织，清空管理部门
				if (key === 'pk_ownerorg_v') {
					let rows = props.cardTable.getVisibleRows(tableId);
					if (rows.length > 0) {
						for (let i = 0; i < rows.length; i++) {
							if (index == i) {
								continue;
							}
							props.cardTable.setValByKeyAndIndex(tableId, i, 'pk_mandept_v', {
								value: null,
								display: null
							});
							props.cardTable.setValByKeyAndIndex(tableId, i, 'pk_mandept', {
								value: null,
								display: null
							});
						}
					}
				}
				//批改使用权，清空使用部门，使用人
				if (key === 'pk_equiporg_v') {
					let rows = props.cardTable.getVisibleRows(tableId);
					if (rows.length > 0) {
						for (let i = 0; i < rows.length; i++) {
							if (index == i) {
								continue;
							}
							props.cardTable.setValByKeyAndIndex(tableId, i, 'pk_usedept', {
								value: null,
								display: null
							});
							props.cardTable.setValByKeyAndIndex(tableId, i, 'pk_assetuser', {
								value: null,
								display: null
							});
						}
					}
				}
			}
		}
	});
}

//表肩增行
export function addLine(props) {
	props.cardTable.addRow(tableId, undefined, {}, true);
	setBodyBtnsEnable.call(this, props, tableId);
}

//表肩删行
function delLine(props) {
	let checkedRows = props.cardTable.getCheckedRows(tableId);
	let checkedIndex = [];
	checkedRows.map((item) => {
		checkedIndex.push(item.index);
	});
	props.cardTable.delRowsByIndex(tableId, checkedIndex);
	setBodyBtnsEnable.call(this, props, tableId);
}

/**
 * 打印
 * @param {*} props 
 */
function printTemp(props) {
	let printData = getPrintData.call(this, props, 'print');
	if (!printData) {
		showMessage.call(this, props, { type: MsgConst.Type.ChoosePrint });
		return;
	}
	print(
		'pdf', // 支持两类：'html'为模板打印，'pdf'为pdf打印
		url.PRINTCARD, // 后台打印服务url
		printData
	);
}

/**
 * 输出
 * @param {*} props 
 */
function outputTemp(props) {
	let printData = getPrintData.call(this, props, 'output');
	if (!printData) {
		showMessage.call(this, props, { type: MsgConst.Type.ChooseOutput });
		return;
	}
	output({
		url: url.PRINTCARD,
		data: printData
	});
}

/**
 * 获取打印数据
 * @param {*} props 
 * @param {*} outputType 
 */
function getPrintData(props, outputType) {
	let pk = props.form.getFormItemsValue(formId, pkField);
	if (!pk || !pk.value) {
		return false;
	}
	let pks = [ pk.value ];
	let printData = {
		filename: getMultiLangByID(printFilename), // 文件名称
		nodekey: printNodekey, // 模板节点标识
		oids: pks, // 需要打印数据主键
		outputType // 输出类型
	};
	return printData;
}

export function doAdd(props) {
	props.cardTable.closeExpandedRow(tableId);
	//设置新增态
	setStatus.call(this, props, UISTATE.add);
	//清空数据
	setValue.call(this, props, undefined);
	//设置默认值
	setDefaultValue.call(this, props);
	// 设置字段编辑性
	let pk_org_v = props.form.getFormItemsValue(formId, 'pk_org_v');
	if (!pk_org_v || !pk_org_v.value) {
		props.initMetaByPkorg('pk_org_v');
	} else {
		//如果财务组织有值，则默认新增一行
		addLine.call(this, props);
	}
	setBodyBtnsEnable.call(this, props, tableId);
}

/**
 * 新增设置默认值
 * @param {*} props 
 */
function setDefaultValue(props) {
	//设置财务组织为可编辑
	props.form.setFormItemsDisabled(formId, { pk_org_v: false });
	//交易类型编码
	let transi_type = getContext(loginContextKeys.transtype);
	// 交易类型主键
	let pk_transitype = getContext(loginContextKeys.pk_transtype);
	//业务日期
	let business_date = getContext(loginContextKeys.businessDate);
	//默认主组织
	let pk_org = getContext(loginContextKeys.pk_org);
	let org_Name = getContext(loginContextKeys.org_Name);
	let pk_org_v = getContext(loginContextKeys.pk_org_v);
	let org_v_Name = getContext(loginContextKeys.org_v_Name);
	//集团
	let groupId = getContext(loginContextKeys.groupId);
	let groupName = getContext(loginContextKeys.groupName);

	props.form.setFormItemsValue(formId, {
		pk_group: { value: groupId, display: groupName },
		bill_status: { display: getMultiLangByID('statusUtils-000000') /* 国际化处理： 自由态*/, value: '0' },
		bill_type: { value: bill_type },
		transi_type: { value: transi_type },
		pk_transitype: { value: pk_transitype },
		business_date: { value: business_date },
		pk_org: { display: org_Name, value: pk_org },
		pk_org_v: { display: org_v_Name, value: pk_org_v },
	});
}

//提交、收回、保存提交
export function commitAction(props, OperatorType, commitType, content, alarmPks) {
	let flag = validateBeforeSave.call(this, props);
	if (!flag) {
		return;
	}
	if (commitType === 'saveCommit') {
		let pk = props.form.getFormItemsValue(formId, pkField).value;
		let CardData = props.createMasterChildDataSimple(pagecode, formId, tableId);
		let paramInfoMap = {};
		paramInfoMap[pk] = ''; //卡片页面ts为空也可以 CardData 里有ts
		let obj = {
			dataType: 'cardData',
			OperatorType: OperatorType,
			commitType: commitType,
			pageid: pagecode,
			paramInfoMap: paramInfoMap,
			content: content,
			userMap: alarmPks && { fa_alarm: 'alarmContinue' }
		};
		CardData.userjson = JSON.stringify(obj);
		props.validateToSave(CardData, () => {
			ajax({
				url: url.COMMIT,
				data: CardData,
				success: (res) => {
					if (content) {
						this.setState({
							compositedisplay: false
						});
					}
					//先判断是否有预警异常
					if (res.data && res.data.userMsgs && Object.keys(res.data.userMsgs).length > 0) {
						handleAlarmException.call(this, res, props, OperatorType, commitType, content);
					} else {
						let callback = () => {
							setStatus.call(this, props, UISTATE.browse);
							setBtnStatusByBillStatus.call(this, props);
						};
						getScriptCardReturnData.call(
							this,
							res,
							props,
							formId,
							tableId,
							pkField,
							dataSource,
							null,
							false,
							callback,
							pagecode
						);
					}
				}
			});
		});
	} else {
		let obj = getCommitParam.call(this, this.props, {
			OperatorType,
			commitType,
			formId: formId,
			tableId: tableId,
			content,
			pageid: pagecode,
			pkField,
			bodyPkField,
			userMap: alarmPks && { fa_alarm: 'alarmContinue' }
		});
		ajax({
			url: url.COMMIT,
			data: obj,
			success: (res) => {
				if (content) {
					this.setState({
						compositedisplay: false
					});
				}
				//先判断是否有预警异常
				if (res.data && res.data.userMsgs && Object.keys(res.data.userMsgs).length > 0) {
					handleAlarmException.call(this, res, props, OperatorType, commitType, content);
				} else {
					let callback = () => {
						setStatus.call(this, props, UISTATE.browse);
						setBtnStatusByBillStatus.call(this, props);
					};
					getScriptCardReturnData.call(
						this,
						res,
						props,
						formId,
						tableId,
						pkField,
						dataSource,
						null,
						false,
						callback,
						pagecode
					);
				}
			}
		});
	}
}

//处理预警异常信息
function handleAlarmException(res, props, OperatorType, commitType, content) {
	let alarmPks = new Set();
	let resData = res.data.errorMsg.split('<br/>');
	let jsx = '';
	jsx = resData.map((item, index) => {
		if (index == 0) {
			return;
		} else if (index == 1) {
			return (
				<div className={`alertMsg-space ${getThemeUtils() + 'theme'}`}>
					<div>
						<span className="iconfont icon-zhuyi1" />
					</div>
					<div>
						<p>{resData[0]}</p>
						<p>{resData[1]}</p>
					</div>
				</div>
			);
		} else {
			return <div className={`${getThemeUtils() + 'theme'}`}>{item}</div>;
		}
	});
	props.modal.show(alarmId, {
		content: jsx,
		beSureBtnClick: () => {
			commitAction.call(this, props, OperatorType, commitType, content, alarmPks);
		}
	});
}

//保存
function doSave(props) {
	//关闭侧拉
	props.cardTable.closeModel(tableId);

	let flag = validateBeforeSave.call(this, props);
	if (!flag) {
		return;
	}

	let cardData = props.createMasterChildDataSimple(pagecode, formId, tableId);
	let reqUrl = url.SAVE; //新增保存
	let oldstatus = props.form.getFormStatus(formId);
	let pk = props.form.getFormItemsValue(formId, pkField).value;
	//判断是新增还是修改
	if (pk && pk != null) {
		reqUrl = url.UPDATE; //修改保存
		oldstatus = UISTATE.edit;
	}
	// 保存前执行验证公式
	props.validateToSave(cardData, () => {
		ajax({
			url: reqUrl,
			data: cardData,
			success: (res) => {
				let { success, data } = res;
				if (success) {
					afterSave.call(this, props, data, oldstatus);
				}
			}
		});
	});
}

/**
* 保存前校验
* @param {*} props 
*/
function validateBeforeSave(props) {
	// 如果是后台默认添加的行，则【dr、rowno】会有值，因此要把这两个值排除在外。
	let mustKeys = [ 'dr', 'rowno', 'pseudocolumn' ];
	// 过滤空行
	props.cardTable.filterEmptyRows(tableId, mustKeys);
	// 表头必输校验
	let flag = props.form.isCheckNow(formId);
	if (!flag) {
		return false;
	}
	// 表体必输校验
	let allRows = props.cardTable.getVisibleRows(tableId);
	if (!allRows || allRows.length == 0) {
		showMessage.call(this, props, { type: MsgConst.Type.ChooseOne });
		return false;
	}
	flag = props.cardTable.checkTableRequired(tableId);
	if (!flag) {
		return false;
	}
	return true;
}

/**
* 保存后处理
* @param {*} props 
*/
export function afterSave(props, data, oldstatus) {
	setValue.call(this, props, data);
	//setStatus.call(this, props, UISTATE.browse); @zhangypmtodo del 重复调用
	let pk = props.form.getFormItemsValue(formId, pkField).value;
	let cachData = this.props.createMasterChildData(pagecode, formId, tableId);
	// 保存成功后处理缓存
	if (oldstatus == UISTATE.add) {
		cardCache.addCache(pk, cachData, formId, dataSource);
		// 设置翻页控件当前id
		props.cardPagination.setCardPaginationId({ id: pk });
	} else {
		cardCache.updateCache(pkField, pk, cachData, formId, dataSource);
	}
	showMessage.call(this, props, { type: MsgConst.Type.SaveSuccess });
	setStatus.call(this, props, UISTATE.browse);
}

//整单保存
export function modelSave(props) {
	doSave.call(this, props);
}

//删除单据
function doDelete(props) {
	let pk = props.form.getFormItemsValue(formId, pkField).value;
	if (!pk) {
		return;
	}
	showConfirm.call(this, props, { type: MsgConst.Type.Delete, beSureBtnClick: singleDel });
}

//删除
function singleDel(props) {
	let pk = props.form.getFormItemsValue(formId, pkField).value;
	let ts = props.form.getFormItemsValue(formId, 'ts').value;
	let cardData = props.createMasterChildDataSimple(pagecode, formId, tableId);
	let paramInfoMap = {
		[pk]: ts
	};
	let obj = {
		dataType: 'cardData',
		OperatorType: 'DELETE',
		commitType: 'commit',
		pageid: pagecode,
		paramInfoMap: paramInfoMap
	};
	cardData.userjson = JSON.stringify(obj);
	ajax({
		url: url.DELETE,
		data: cardData,
		success: (res) => {
			let { success } = res;
			if (success) {
				let callback = (newpk) => {
					// 更新参数
					props.setUrlParam({ id: newpk });
					// 加载下一条数据
					loadDataByPk.call(this, props, newpk);
				};
				getScriptCardReturnData.call(
					this,
					res,
					props,
					formId,
					tableId,
					pkField,
					dataSource,
					undefined,
					true,
					callback,
					pagecode
				);
			}
		}
	});
}

/**
 * 设置复制界面状态
 * @param {*} props 
 * @param {*} status 
 */
export function setCopyStatus(props, status = UISTATE.add) {
	props.form.setFormStatus(formId, status);
	props.cardTable.setStatus(tableId, UISTATE.edit);
	// 先隐藏后显示，解决浏览态编辑态都有的按钮清空
	setBrowseBtnsVisible.call(this, props);
	props.button.setButtonVisible(editBtns, true);
	setBodyBtnsEnable.call(this, props, tableId);
}

/**
 * 设置界面状态
 * @param {*} props 
 * @param {*} status 
 */
export function setStatus(props, status = UISTATE.browse) {
	switch (status) {
		case UISTATE.add:
			props.form.setFormStatus(formId, status);
			props.cardTable.setStatus(tableId, UISTATE.edit);
			// 先隐藏后显示，解决浏览态编辑态都有的按钮清空
			setBrowseBtnsVisible.call(this, props);
			props.button.setButtonVisible(editBtns, true);
			setBodyBtnsEnable.call(this, props, tableId);
			break;
		case UISTATE.edit:
			props.form.setFormStatus(formId, status);
			props.cardTable.setStatus(tableId, status);
			// 先隐藏后显示，解决浏览态编辑态都有的按钮清空
			setBrowseBtnsVisible.call(this, props);
			props.button.setButtonVisible(editBtns, true);
			setBodyBtnsEnable.call(this, props, tableId);
			break;
		case UISTATE.browse:
			props.form.setFormStatus(formId, status);
			props.cardTable.setStatus(tableId, status);
			// 先隐藏后显示，解决浏览态编辑态都有的按钮清空
			props.button.setButtonVisible(editBtns, false);
			setBrowseBtnsVisible.call(this, props);
			break;
		default:
			break;
	}
	// 根据 saga 状态控制按钮状态
	setBtnsVisibleBySagaStatus.call(this, props, {billpkname: pkField});
	setHeadAreaData.call(this, props, { status });
}

//取消
function doCancel(props) {
	showConfirm.call(this, props, { type: MsgConst.Type.Cancel, beSureBtnClick: singleCancel });
}

function singleCancel(props) {
	//设置字段可编辑性
	let pk_org_v = props.form.getFormItemsValue(formId, 'pk_org_v');
	if (!pk_org_v || !pk_org_v.value) {
		props.resMetaAfterPkorgEdit();
	}
	props.form.cancel(formId);
	props.cardTable.resetTableData(tableId);
	setStatus.call(this, props, UISTATE.browse);
	//设置财务组织为可编辑
	//props.form.setFormItemsDisabled(formId, { pk_org_v: false });
	// 加载编辑前数据，如果编辑前没有数据，则加载当前列表最后一条数据，如果还没有，显示为空不处理
	let pk = props.form.getFormItemsValue(formId, pkField).value;
	if (!pk) {
		pk = cardCache.getCurrentLastId(dataSource);
	}
	// 设置翻页控件当前id
	props.cardPagination.setCardPaginationId({ id: pk });
	loadDataByPk.call(this, props, pk);
}

/**
 * 刷新 
 */
function refresh(props) {
	let pk = props.form.getFormItemsValue(formId, pkField).value;
	if (!pk) {
		return;
	}
	let callback = (data) => {
		if (data) {
			showMessage.call(this, props, { type: MsgConst.Type.RefreshSuccess });
		}
	};
	getDataByPk.call(this, props, pk, callback);
}

/**
 * 根据单据状态设置部分按钮可见性
 * @param {*} props 
 * @param {*} bill_status 
 */
export function setBtnStatusByBillStatus(props) {
	setBillFlowBtnsVisible.call(this, props, formId, pkField);
}

/**
 * 通过单据id获取缓存单据信息，没有缓存则重新查询
 * @param {*} props 
 * @param {*} pk 
 */
export function loadDataByPk(props, pk, callback) {
	if (!pk || pk == 'null') {
		setValue.call(this, props, undefined);
		typeof callback == 'function' && callback();
	} else {
		let cachData = cardCache.getCacheById(pk, dataSource);
		if (cachData) {
			setValue.call(this, props, cachData);
			typeof callback == 'function' && callback(cachData);
		} else {
			getDataByPk.call(this, props, pk, callback);
		}
	}
}

/**
 * 通过单据id查询单据信息
 * @param {*} props 
 * @param {*} pk 
 */
export function getDataByPk(props, pk, callback) {
	ajax({
		url: url.QUERY_CARD,
		data: {
			pagecode,
			pk
		},
		success: (res) => {
			let { success, data } = res;
			if (success) {
				if (data) {
					setValue.call(this, props, data);
					cardCache.updateCache(pkField, pk, data, formId, dataSource);
				} else {
					setValue.call(this, props, undefined);
					cardCache.deleteCacheById(pkField, pk, dataSource);
					showMessage.call(this, props, { type: MsgConst.Type.DataDeleted });
				}
				typeof callback == 'function' && callback(data);
			}
		}
	});
}

/**
 * 设置界面值
 * @param {*} props 
 * @param {*} data 
 */
export function setValue(props, data) {
	setCardValue.call(this, props, data);
	let status = props.form.getFormStatus(formId);
	setStatus.call(this, props, status);
	//setBrowseBtnsVisible.call(this, props);
}

/**
* 返回
* @param {*} props 
*/
export function backToList(props) {
	props.pushTo(listRouter, {
		pagecode: pagecode.replace('card', 'list')
	});
}

/**
 * 浏览态设置按钮显示隐藏
 * @param {*} props 
 */
function setBrowseBtnsVisible(props) {
	let status = props.form.getFormStatus(formId) || UISTATE.browse;
	if (status != UISTATE.browse) {
		props.button.setButtonVisible(browseBtns, false);
	} else {
		let pkVal = props.form.getFormItemsValue(formId, pkField);
		if (!pkVal || !pkVal.value) {
			props.button.setButtonVisible(browseBtns, false);
			props.button.setButtonVisible('Add', true);
			return;
		}
		props.button.setButtonVisible(browseBtns, true);
		setBillFlowBtnsVisible.call(this, props, formId, pkField);
	}
}

/**
 * 设置表体按钮是否可用
 * @param {*} props 
 * @param {*} moduleId 
 */
export function setBodyBtnsEnable(props, moduleId) {
	let pk_org_v = props.form.getFormItemsValue(formId, 'pk_org_v');
	if (!pk_org_v || !pk_org_v.value) {
		props.button.setButtonDisabled([ 'AddLine', 'DelLine', 'BatchAlter' ], true);
	} else {
		props.button.setButtonDisabled([ 'AddLine', 'BatchAlter' ], false);
		let checkedRows = [];
		let num = props.cardTable.getNumberOfRows(moduleId, false);
		if (num > 0) {
			checkedRows = props.cardTable.getCheckedRows(moduleId);
		}
		props.button.setButtonDisabled([ 'DelLine' ], !(checkedRows && checkedRows.length > 0));
	}
}

//得到不重复的 数组中元素的的某个属性值
function getArrayAttribute(ary, attr) {
	let set = new Set();
	ary.map((item) => {
		if (item[attr]) {
			set.add(item[attr]);
		} else {
			set.add('');
		}
	});
	return [ ...set ];
}

/*Hm9gUKDDwtNjV7Mk8onAzgXlk2sN3YqGeiNBfMPmEAaQ5tb/cjXQzjs3lVWuDzNj*/